package com.ecjtu.stadiumre_servations.service.impl;




import com.ecjtu.stadiumre_servations.entity.domain.Booking;
import com.ecjtu.stadiumre_servations.mapper.BookingMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BookingAnalysisService {

    @Autowired
    private BookingMapper bookingMapper;

    // 日期格式化工具
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    /**
     * 分析用户预约习惯
     */
    public String analyzeUserBookingHabit(String studentId) {
        // 查询用户最近5条预约记录
        List<Booking> recentBookings = bookingMapper.findRecentBookingsByStudentId(studentId, 5);

        if (recentBookings.isEmpty()) {
            return "您还没有任何预约记录。";
        }

        StringBuilder analysis = new StringBuilder();
        analysis.append("您最近的预约记录：\n");

        // 构建最近预约记录
        for (Booking booking : recentBookings) {
            analysis.append("- 预约时间：")
                    .append(booking.getBookingStartTime().format(formatter))
                    .append(" ~ ")
                    .append(booking.getBookingEndTime().format(formatter))
                    .append("，场地：")
                    .append(booking.getVenueId())
                    .append("，类型：")
                    .append(booking.getBookingType())
                    .append("，状态：")
                    .append(booking.getBookingStatus())
                    .append("\n");
        }

        // 统计总预约次数
        long totalBookings = bookingMapper.countBookingsByStudentId(studentId);
        analysis.append("\n您总共进行了").append(totalBookings).append("次预约。\n");

        // 分析偏好场地
        Map<String, Long> venueCount = recentBookings.stream()
                .collect(Collectors.groupingBy(Booking::getVenueId, Collectors.counting()));
        String favoriteVenue = getMostFrequentVenue(venueCount);
        analysis.append("您最常使用的场地是：").append(favoriteVenue).append("\n");

        // 计算总消费
        double totalSpending = bookingMapper.calculateTotalSpendingByStudentId(studentId);
        analysis.append("您的总消费金额为：").append(totalSpending).append("元\n");

        // 分析时段偏好
        String timePreference = analyzeTimePreference(recentBookings);
        analysis.append("您的预约时段偏好：").append(timePreference);

        return analysis.toString();
    }

    /**
     * 获取最常使用的场地
     */
    private String getMostFrequentVenue(Map<String, Long> venueCount) {
        if (venueCount.isEmpty()) {
            return "无";
        }

        return venueCount.entrySet().stream()
                .max(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .orElse("无");
    }

    /**
     * 分析时段偏好
     */
    private String analyzeTimePreference(List<Booking> bookings) {
        // 按小时统计预约次数
        Map<Integer, Integer> hourCount = new HashMap<>();
        for (Booking booking : bookings) {
            int hour = booking.getBookingStartTime().getHour();
            hourCount.put(hour, hourCount.getOrDefault(hour, 0) + 1);
        }

        if (hourCount.isEmpty()) {
            return "无明显时段偏好";
        }

        // 找出最频繁的时段
        Map.Entry<Integer, Integer> mostFrequent = hourCount.entrySet().stream()
                .max(Map.Entry.comparingByValue())
                .orElse(null);

        if (mostFrequent == null) {
            return "无明显时段偏好";
        }

        // 定义时段描述
        String timeDescription;
        if (mostFrequent.getKey() < 12) {
            timeDescription = "上午";
        } else if (mostFrequent.getKey() < 18) {
            timeDescription = "下午";
        } else {
            timeDescription = "晚上";
        }

        return timeDescription + "（" + mostFrequent.getKey() + ":00左右）";
    }

    /**
     * 分析场地使用趋势
     */
    public String analyzeVenueUsageTrend(String studentId, int months) {
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.minusMonths(months);

        List<Booking> bookings = bookingMapper.findBookingsByStudentIdAndTimeRange(
                studentId, startTime, endTime);

        if (bookings.isEmpty()) {
            return "近" + months + "个月内没有预约记录。";
        }

        // 按月份统计各场地预约次数
        Map<String, Map<Integer, Integer>> venueMonthlyCount = new HashMap<>();

        for (Booking booking : bookings) {
            String venueId = booking.getVenueId();
            int month = booking.getBookingStartTime().getMonthValue();

            venueMonthlyCount.computeIfAbsent(venueId, k -> new HashMap<>())
                    .put(month, venueMonthlyCount.get(venueId).getOrDefault(month, 0) + 1);
        }

        StringBuilder trendAnalysis = new StringBuilder("近" + months + "个月场地使用趋势：\n");

        for (Map.Entry<String, Map<Integer, Integer>> entry : venueMonthlyCount.entrySet()) {
            trendAnalysis.append("- 场地 ").append(entry.getKey()).append(": ");
            List<Integer> monthsList = new ArrayList<>(entry.getValue().keySet());
            Collections.sort(monthsList);

            for (int month : monthsList) {
                trendAnalysis.append(month).append("月").append(entry.getValue().get(month)).append("次 ");
            }
            trendAnalysis.append("\n");
        }

        return trendAnalysis.toString();
    }
}